console.log('js/index.js loaded');
// 全局变量存储数据
let allData = [];
let data = [];
let theRequest = {};

// 在页面加载时获取数据
window.onload = async function () {
    console.log('window loaded');
    try {
        // 使用 async/await 获取数据
        const response = await fetch('data/data.json');
        allData = await response.json();

        // 获取 URL 参数并处理数据
        let url = location.search;

        if (url.indexOf("?") != -1) {
            let str = url.substr(1);
            let strs = str.split("&");
            for (let i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
            }
            window.name = theRequest.name;
            if (theRequest.index) {
                data = outData(allData, theRequest.index);
            }
        } else {
            data = outData(allData, 0);
        }

        // 预加载首屏图片
        const firstScreenImages = getFirstScreenImages(data);
        if (window.preloadImages) {
            window.preloadImages(firstScreenImages);
        }

        // 初始化页面内容
        initializeContent();

    } catch (error) {
        console.error('Error loading JSON:', error);
    }
}

// 获取首屏需要预加载的图片
function getFirstScreenImages(data) {
    const images = [];
    if (data && data.length > 0) {
        // 添加第一个卡片组的图片
        if (data[0].list && data[0].list.length > 0) {
            // 只预加载前4张图片
            for (let i = 0; i < Math.min(4, data[0].list.length); i++) {
                images.push(`./images/${data[0].list[i].img}`);
            }
        }
    }
    return images;
}

// 处理数据的函
export function outData(allData, index) {
    let data = JSON.parse(JSON.stringify(allData));
    for (let i = 0; i < allData.length; i++) {
        if (allData[i].list[index]) {
            data[i].list = JSON.parse(JSON.stringify(allData[i].list[index]));
        } else {
            data[i].list = JSON.parse(JSON.stringify(allData[i].list[0]));
        }
    }
    return data;
}

// 初始化页面内容的函数
function initializeContent() {
    let oCards = document.querySelectorAll('.card_one');
    for (let x = 0; x < oCards.length; x++) {
        let oList = '';
        for (let i = 0; i < 8; i++) {
            if (!data[x]?.list[i]) continue; // 检查数据是否存在
            const imgSrc = `./images/${data[x].list[i].img}`;
            oList +=
                `<li class="card_item">
                    <img 
                        src="${imgSrc}"
                        alt="${data[x].list[i].name}"
                        loading="lazy"
                        onload="this.classList.add('loaded')"
                        onerror="this.onerror=null; this.src='./images/placeholder.png'; this.classList.add('img-error');"
                    >
                    <p>
                        <span>
                            ${data[x].list[i].text}
                        </span>
                    </p>
                </li>`;
        }
        oCards[x].innerHTML = `<div class="card_header">
                            <h2>${data[x].text}</h2>
                        </div>
                        <div class="card_list">
                            <div class="left">
                                <img 
                                    src="./images/Left.PNG"
                                    alt="Previous"
                                    onload="this.classList.add('loaded')"
                                    onerror="this.onerror=null; this.src='./images/placeholder.png'; this.classList.add('img-error');"
                                >
                            </div>
                            <ul>
                            ${oList}
                            </ul>
                            <div class="right">
                                <img 
                                    src="./images/Right.PNG"
                                    alt="Next"
                                    onload="this.classList.add('loaded')"
                                    onerror="this.onerror=null; this.src='./images/placeholder.png'; this.classList.add('img-error');"
                                >
                            </div>
                        </div>`;

        let allLi = oCards[x].querySelectorAll("li");
        for (let i = 0; i < allLi.length; i++) {
            allLi[i].addEventListener('click', (e) => {
                e.preventDefault();
                gotoFrom(data[x].id, data[x].list[i].name);
            });
        }
    }

    // 初始化滚动功能
    initializeScroll();
    // 监控图片加载
    monitorImagesLoading();
}

// 监控图片加载状态
function monitorImagesLoading() {
    const images = document.querySelectorAll('img');
    let loadedCount = 0;
    const totalCount = images.length;

    images.forEach(img => {
        if (img.complete) {
            loadedCount++;
        } else {
            img.addEventListener('load', () => {
                loadedCount++;
                console.log(`Image loaded: ${loadedCount}/${totalCount}`);
            });
            img.addEventListener('error', () => {
                loadedCount++;
                console.log(`Image failed: ${loadedCount}/${totalCount}`);
            });
        }
    });
}

// 初始化滚动功能
function initializeScroll() {
    let oCard_List = document.querySelectorAll('.card_list');
    let scrollAmounts = new Array(oCard_List.length).fill(0);

    oCard_List.forEach((cardList, index) => {
        const ul = cardList.querySelector('ul');
        const leftBtn = cardList.querySelector('.left');
        const rightBtn = cardList.querySelector('.right');
        const scrollStep = 575;

        leftBtn.addEventListener('click', () => {
            scrollAmounts[index] = Math.max(0, scrollAmounts[index] - scrollStep);
            ul.scrollTo({
                left: scrollAmounts[index],
                behavior: 'smooth'
            });
        });

        rightBtn.addEventListener('click', () => {
            const maxScroll = ul.scrollWidth - ul.clientWidth;
            scrollAmounts[index] = Math.min(maxScroll, scrollAmounts[index] + scrollStep);
            ul.scrollTo({
                left: scrollAmounts[index],
                behavior: 'smooth'
            });
        });

        ul.addEventListener('scroll', () => {
            scrollAmounts[index] = ul.scrollLeft;
        });
    });
}

// 其他功能函数
let isShow = false;
export function ShowSearch() {
    isShow = !isShow;
    document.querySelector('.search').style.display = isShow ? 'block' : 'none';
}

let isshow_list = false;
export function show_content() {
    isshow_list = !isshow_list;
    document.querySelector('.header .left>ul').style.display = isshow_list ? 'block' : 'none';
}

function gotoFrom(id, item) {
    const index = new URLSearchParams(location.search).get('index') || 0;
    location.href = `./pages/from.html?id=${id}&name=${item}&index=${index}`;
}

// 顶部导航点击事件
let oHeader = document.querySelectorAll('.header_list>li');
for (let i = 0; i < oHeader.length; i++) {
    oHeader[i].addEventListener('click', (e) => {
        e.preventDefault();
        // console.log(index.html)
        const currentPath = window.location.pathname;
        if (currentPath.includes('/pages/')) {
            location.href = `../index.html?index=${i}`;
        } else {
            location.href = `index.html?index=${i}`;
        }
    });
}

// 登录框相关功能
let isLoginShow = false;
export function showLogin() {
    const loginModal = document.getElementById('loginModal');
    if (!loginModal) {
        // 如果登录框不存在，则创建
        createLoginModal();
    }
    isLoginShow = !isLoginShow;
    document.getElementById('loginModal').style.display = isLoginShow ? 'block' : 'none';
}

//<span class="close" onclick="window.closeLogin()">&times;</span>
// 创建登录框
function createLoginModal() {
    const modalHtml = `
            <div id="loginModal" class="modal">
        <div class="modal-content">

            <h2>Create a new account</h2>
            <form>
                <div class="form-group">
                    <label for="username"></label>
                    <input type="text" id="username" name="username" placeholder="Email" required>
                </div>
                <div class="form-group">
                    <label for="password"></label>
                    <input type="password" id="password" name="password" placeholder="Password" required>
                </div>
                <div class="form-group">
                    <label for="compassword"></label>
                    <input type="password" id="compassword" name="compassword" placeholder="Confirm Password" required>
                </div>
                <button type="submit" class="login-btn">CREATE ACCOUNT</button>
                <div class="divider">
                    <span>or</span>
                </div>
                <button type="submit" class="login-btn">Sign up width Facebook</button>
                <div class="form-group the-check">
                    <input type="checkbox" id="check" name="check">
                    <label for="check">
                        I have read and agree to the <a href="#">Terms of Service</a> and <a href="#">Privacy
                            Policy</a>.I agree
                        to be contacted about updates of the service I may like unless I click to opt out</label>
                </div>
                <div class="form-group-or-login">
                    <label for="check">or <a href="#">Login</a></label>
                </div>
            </form>
        </div>
    </div>
    `;
    document.body.insertAdjacentHTML('beforeend', modalHtml);

    // 添加关闭事件
    window.closeLogin = function () {
        isLoginShow = false;
        document.getElementById('loginModal').style.display = 'none';
    };

    // 点击模态框外部关闭
    document.getElementById('loginModal').addEventListener('click', function (event) {
        if (event.target === this) {
            window.closeLogin();
        }
    });
}

// 为login添加点击事件
document.addEventListener('DOMContentLoaded', function () {
    const loginButton = document.querySelector('.login');
    if (loginButton) {
        loginButton.addEventListener('click', showLogin);
    }
});